function rowToTreeitem(item) {
  let result = {
    children: []
  }
  for (let i in item) {
    result[i] = item[i]
  }
  return result;
}

//数组 转 树
function dataToTree(data) {

  let arr = [];

  if (!data) {
    return arr;
  }

  let recursionTree = function (arr, pid, data) {
    for (let item of data) {

      if (item.parentId == pid || (pid == undefined && item.parentId == '')) {
        let tree = rowToTreeitem(item);
        arr.push(tree);
        if (tree.id) {
          recursionTree(tree.children, tree.id, data);
        }
      }
    }
  }
  recursionTree(arr, undefined, data);
  return arr;
}

function treeToRows(data) {
  let weight = 1;
  let recursionTree = function (arr, data) {
    for (let item of data) {
      item.weight = weight++;
      if (item.children && item.children.length){
        recursionTree(arr, item.children);
        delete item.children
      }

      arr.push(item);
    }
  }
  let arr = [];
  recursionTree(arr, data);
  return arr;
}

function upMoveTree(trees, row) {
  let rows = treeToRows(trees);
  if (rows && rows.length > 0) {
    let pid = row.parentId;
    let oldRow = undefined;
    for (let item of rows) {
      if (item.id == row.id) {
        if (oldRow != undefined) {
          let tmp = {};
          copyObj(oldRow, tmp);
          copyObj(item, oldRow);
          copyObj(tmp, item);
        }
        break;
      }
      if (item.parentId == pid) {
        oldRow = item;
      }
    }
    //排序
    for (let i = 1; i < rows.length; i++) {
      rows[i].weight = i
    }
  }
  return rows;
}

function copyObj(sources, target) {
  for (let item in sources) {
    target[item] = sources[item]
  }
}

export {
  dataToTree, treeToRows, upMoveTree
}
